﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SocialApi.Core.Extensions;

namespace SocialApi.Instagram.Converters
{
    /// <summary>
    /// Преобразует UNIX формат в <see cref="DateTime" />
    /// </summary>
    public class UnixDateTimeConverter : DateTimeConverterBase
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            double val;
            if (value is DateTime)
            {
                val = ((DateTime)value).ToUnixTimestamp();
            }
            else
            {
                throw new Exception("Expected date object value.");
            }

            writer.WriteValue(val);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return reader.Value.ConvertTo<double>().ToDateTimeTimestamp();
        }
    }
}